<template>
  <div class="new-notification-container">
    <div class="form-header">
      <h2>发布新通知</h2>
    </div>
    
    <el-form :model="notificationForm" :rules="rules" ref="notificationForm" label-width="100px" class="notification-form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="notificationForm.title" placeholder="请输入通知标题"></el-input>
      </el-form-item>
      
      <el-form-item label="消息类型" prop="message_type">
        <el-select v-model="notificationForm.message_type" placeholder="请选择消息类型" style="width: 100%" @change="handleMessageTypeChange">
          <el-option label="园区公告" value="园区公告"></el-option>
          <el-option label="新闻资讯" value="新闻资讯"></el-option>
          <el-option label="审批提醒" value="审批提醒"></el-option>
          <el-option label="业务提醒" value="业务提醒"></el-option>
          <el-option label="合同提醒" value="合同提醒"></el-option>
          <el-option label="缴费提醒" value="缴费提醒"></el-option>
          <el-option label="活动推广" value="活动推广"></el-option>
          <el-option label="系统通知" value="系统通知"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="目标受众" prop="target_audience">
        <div class="audience-selection">
          <div class="audience-groups">
            <el-checkbox-group v-model="notificationForm.target_groups" class="checkbox-container">
              <el-checkbox label="企业员工">企业员工</el-checkbox>
              <el-checkbox label="物业员工">物业员工</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="specific-users-section">
            <div class="specific-users-header">
              <span class="section-title">特定用户：</span>
              <el-select 
                v-model="notificationForm.specific_users" 
                multiple 
                filterable 
                remote 
                reserve-keyword
                :remote-method="searchUsers" 
                :loading="searchLoading"
                placeholder="输入用户名、手机号或企业名搜索" 
                style="width: calc(100% - 85px)">
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <div class="user-option">
                    <span>{{ item.label }}</span>
                    <small>{{ item.type }}</small>
                  </div>
                </el-option>
                <template v-if="userOptions.length === 0 && searchQuery && !searchLoading" #empty>
                  <div class="no-result">
                    未找到匹配"{{ searchQuery }}"的用户或企业
                  </div>
                </template>
              </el-select>
            </div>
            <div class="form-tip">
              可搜索并选择特定用户或企业进行精准推送
            </div>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="有效期">
        <div style="display: flex; align-items: center; gap: 10px;">
          <el-form-item prop="valid_from" style="margin-bottom: 0; width: 50%;">
            <el-date-picker
              v-model="notificationForm.valid_from"
              type="datetime"
              placeholder="开始日期"
              :value-format="dateValueFormat"
              :format="dateDisplayFormat"
              style="width: 100%"
              @change="handleDateChange('valid_from')">
            </el-date-picker>
          </el-form-item>
          <span>至</span>
          <el-form-item prop="valid_until" style="margin-bottom: 0; width: 50%;">
            <el-date-picker
              v-model="notificationForm.valid_until"
              type="datetime"
              placeholder="结束日期"
              :value-format="dateValueFormat"
              :format="dateDisplayFormat"
              style="width: 100%"
              @change="handleDateChange('valid_until')">
            </el-date-picker>
          </el-form-item>
        </div>
      </el-form-item>
      
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          v-model="notificationForm.content"
          :rows="10"
          placeholder="请输入通知内容">
        </el-input>
      </el-form-item>
      
      <el-form-item class="form-buttons">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { createNotification } from '@/api/notifications';
import { searchUsers } from '@/api/users';

export default {
  name: 'NotificationPublish',
  data() {
    // 日期格式化函数
    const formatDateToString = (date) => {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day} 00:00:00`;
    };

    // 获取当前日期和结束日期（7天后）
    const now = new Date();
    const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    
    return {
      notificationForm: {
        title: '',
        content: '',
        message_type: '',
        valid_from: formatDateToString(now),
        valid_until: formatDateToString(nextWeek),
        target_groups: [],
        specific_users: []
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
        ],
        message_type: [
          { required: true, message: '请选择消息类型', trigger: 'change' }
        ],
        valid_from: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        valid_until: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 10, max: 5000, message: '长度在 10 到 5000 个字符', trigger: 'blur' }
        ]
      },
      // 不同消息类型推荐的目标受众
      audienceRecommendations: {
        '园区公告': ['企业员工', '物业员工'],
        '新闻资讯': ['企业员工'],
        '审批提醒': ['企业员工'],
        '业务提醒': ['企业员工', '物业员工'],
        '合同提醒': ['企业员工'],
        '缴费提醒': ['企业员工'],
        '活动推广': ['企业员工'],
        '系统通知': ['企业员工', '物业员工']
      },
      userOptions: [],
      searchLoading: false,
      searchQuery: '',
      searchTimeout: null,
      isSubmitting: false,
      dateValueFormat: 'yyyy-MM-dd HH:mm:ss',
      dateDisplayFormat: 'yyyy-MM-dd HH:mm:ss'
    };
  },
  methods: {
    submitForm() {
      this.$refs.notificationForm.validate(async (valid) => {
        if (valid) {
          // 检查是否至少选择了一个目标受众
          if (!this.validateAudience()) {
            this.$message.error('请至少选择一个目标群体或特定用户');
            return false;
          }
          
          // 再次验证日期格式
          if (this.notificationForm.valid_from.includes('yyyy') || 
              this.notificationForm.valid_until.includes('yyyy') ||
              /\b(Mo|Tu|We|Th|Fr|Sa|Su)\b/.test(this.notificationForm.valid_from) ||
              /\b(Mo|Tu|We|Th|Fr|Sa|Su)\b/.test(this.notificationForm.valid_until)) {
            
            // 格式化日期
            const now = new Date();
            const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
            this.notificationForm.valid_from = this.formatDate(now);
            this.notificationForm.valid_until = this.formatDate(nextWeek);
            
            console.warn('检测到无效的日期格式，已自动修正:');
            console.log('开始时间:', this.notificationForm.valid_from);
            console.log('结束时间:', this.notificationForm.valid_until);
          }
          
          // 防止重复提交
          if (this.isSubmitting) {
            return;
          }
          
          this.isSubmitting = true;
          
          try {
            // 检查有效期格式
            if (!this.notificationForm.valid_until) {
              console.warn('有效期结束时间未设置');
            } else {
              console.log('提交的有效期结束时间:', this.notificationForm.valid_until);
            }
            
            const formData = {
              title: this.notificationForm.title,
              content: this.notificationForm.content,
              message_type: this.notificationForm.message_type,
              valid_from: this.notificationForm.valid_from,
              valid_until: this.notificationForm.valid_until,
              target_groups: this.notificationForm.target_groups,
              specific_users: this.notificationForm.specific_users
            };
            
            // 打印要发送的数据，用于调试
            console.log('提交的表单数据:', JSON.stringify(formData));

            const response = await createNotification(formData);
            
            if (response.data && (response.data.code === 201 || response.data.code === 200)) {
              this.$message.success('通知发布成功');
              this.resetForm();
              // 延迟跳转，避免消息重叠
              setTimeout(() => {
                this.$router.push({ name: 'NotificationManagement' });
              }, 1500);
            } else {
              const errorMsg = response.data ? response.data.message : '发布失败，请重试';
              this.$message.error(errorMsg);
              console.error('发布失败，服务器响应:', response);
            }
          } catch (error) {
            console.error('提交表单时出错:', error);
            this.$message.error('发布失败，请重试');
          } finally {
            this.isSubmitting = false;
          }
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.notificationForm.resetFields();
    },
    handleMessageTypeChange() {
      const messageType = this.notificationForm.message_type;
      if (messageType && this.audienceRecommendations[messageType]) {
        // 自动设置推荐的目标受众
        this.notificationForm.target_groups = this.audienceRecommendations[messageType];
      }
    },
    searchUsers(query) {
      this.searchQuery = query;
      if (query.length < 2) {
        this.userOptions = [];
        return;
      }
      
      // 清除之前的定时器（防抖）
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      
      // 设置定时器延迟300毫秒执行搜索（防抖）
      this.searchTimeout = setTimeout(() => {
        this.searchLoading = true;
        
        searchUsers(query).then(response => {
          if (response.data && response.data.code === 200) {
            this.userOptions = response.data.data.map(item => {
              return {
                value: item.id,
                label: item.name || item.username,
                type: item.type
              };
            });
          } else {
            this.userOptions = [];
          }
        }).catch(() => {
          this.userOptions = [];
        }).finally(() => {
          this.searchLoading = false;
        });
      }, 300);
    },
    validateAudience() {
      const hasGroups = this.notificationForm.target_groups && this.notificationForm.target_groups.length > 0;
      const hasUsers = this.notificationForm.specific_users && this.notificationForm.specific_users.length > 0;
      return hasGroups || hasUsers;
    },
    handleDateChange(field) {
      console.log(`${field}变更为: `, this.notificationForm[field]);
      
      // 确保日期格式正确
      if (this.notificationForm[field] && typeof this.notificationForm[field] === 'string') {
        // 如果检测到错误格式的日期字符串(包含'yyyy'或星期简写)，重置为当前日期
        if (this.notificationForm[field].includes('yyyy') || 
            /\b(Mo|Tu|We|Th|Fr|Sa|Su)\b/.test(this.notificationForm[field])) {
          
          console.warn(`检测到无效的日期格式: ${this.notificationForm[field]}`);
          
          // 重置为当前日期或当前日期+7天
          const now = new Date();
          if (field === 'valid_from') {
            this.notificationForm[field] = this.formatDate(now);
          } else if (field === 'valid_until') {
            const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
            this.notificationForm[field] = this.formatDate(nextWeek);
          }
        }
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day} 00:00:00`;
    }
  },
  mounted() {
    // 组件挂载后，确保日期格式正确
    const now = new Date();
    const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    
    // 重新设置日期以确保格式正确
    this.notificationForm.valid_from = this.formatDate(now);
    this.notificationForm.valid_until = this.formatDate(nextWeek);
    
    console.log('组件初始化完成，设置的日期值:');
    console.log('开始时间:', this.notificationForm.valid_from);
    console.log('结束时间:', this.notificationForm.valid_until);
  },
  watch: {
    'notificationForm.target_groups': function() {
      if (this.notificationForm.target_groups.includes('所有人')) {
        this.notificationForm.target_groups = ['所有人'];
        this.notificationForm.specific_users = [];
      }
    }
  }
};
</script>

<style scoped>
.new-notification-container {
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  margin-bottom: 30px;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 15px;
}

.notification-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-buttons {
  text-align: right;
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}

.audience-selection {
  display: flex;
  flex-direction: row;
  gap: 15px;
  margin-bottom: 15px;
}

.audience-groups {
  flex: 3;
  padding: 10px 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.specific-users-section {
  flex: 5;
  padding: 10px 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.checkbox-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.audience-groups .el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}

.section-title {
  font-size: 14px;
  color: #606266;
  margin-top: 0;
  margin-bottom: 10px;
  font-weight: 500;
  display: inline-block;
  min-width: 75px;
}

.specific-users-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.specific-users-header .el-select {
  margin-left: 5px;
}

.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 5px;
}

.user-option span {
  font-weight: 500;
}

.user-option small {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

.no-result {
  text-align: center;
  padding: 10px 0;
  color: #909399;
  font-size: 14px;
}
</style> 